#import packages
from scipy.spatial import distance as dist
from collections import OrderedDict
import numpy as np
import cv2

class Colordetector:
	#initialize the basic dictionary, colorspace, parameters
	def __init__(self):
		#initialize colors dictionary, name as key and RGB as value
		colors = OrderedDict({
			"red": (255,0,0),
			"green": (0,255,0),
			"blue": (0,0,255),
			#"orange": (255,165,0),
			#"yellow": (255,255,0),
			#"purple": (139,0,255),
			#"cyan_blue": (0,127,255)
		})
		
		#allocate memory for LAB image, initial color name list
		self.lab = np.zeros((len(colors),1,3), dtype="uint8")
		self.colornames = []
		
		#loop over dictionary
		for (i,(name,rgb)) in enumerate(colors.items()):
			#update lab array and colornamelst
			self.lab[i] = rgb
			self.colornames.append(name)
			#checkpoint
			#print(self.colornames)
			#convert color space
		self.lab = cv2.cvtColor(self.lab, cv2.COLOR_RGB2LAB)
		#checkpoint
		#print(self.lab)
	#work of labeling
	def label(self, image, c):
		#construct a mask for the contour then calculate the average LAB value for teh region
		mask = np.zeros(image.shape[:2], dtype="uint8")
		cv2.drawContours(mask, [c], -1, 255, -1)
		mask = cv2.erode(mask, None, iterations=2)
		mean = cv2.mean(image, mask=mask)[:3]
		#checkpoint2
		#print(mean)
		#cv2.waitKey(0)
		
		#initialize the min dist found
		minDist = (np.inf, None)
		
		#loop over LAB vaule in dictionary
		for (i,row) in enumerate(self.lab):
			#compute the dist between LAB dict and mean of image
			d = dist.euclidean(row[0], mean)
			
			#if dist is smaller than update
			if d < minDist[0]:
				minDist = (d,i)
			#checkpoint3
			#print(minDist[1])
		#return the name of color
		return self.colornames[minDist[1]]
	
		
			
		